package manager.server{
	import com.debug.TDebug;
	
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.ObjectEncoding;
	import flash.net.Socket;
	import flash.system.Security;
	
	import manager.server.event.SocketEvent;
	
	import org.adobe.utils.Singleton;

	/**
	 * Socket基类
	 * 该类为Socket的基类，
	 * 内部仅重写和对服务器的响应做了简单的判断
	 * 派出套接字接收到数据事件
	 * 
	 */	
	public class SocketBase extends Socket {
		
		public function SocketBase(){
			/**AMF3只在写Object时才会用到,用于约定通信协议**/
			this.objectEncoding = ObjectEncoding.AMF3;
			
			/**监听Socket加载过程中的所有事件**/
			this.addEventListener(Event.CONNECT, onConnect);
			this.addEventListener(Event.CLOSE, onClose);
			this.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			this.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
			this.addEventListener(ProgressEvent.SOCKET_DATA, onData);
		}

		/**重写connect方法，其中加入策略文件的加载**/
		override public function connect(host:String, port:int):void {
			Security.loadPolicyFile("xmlsocket://" + host + ":" + port);
			super.connect(host, port);
			TDebug.trace("连接地址为:" + host,"port:" + port);
		}

		/**关闭当前socket连接**/
		override public function close():void {
			if (this.connected){
				super.close();
			}
		}

		/**对socket数据的更新进行监听操作**/
		private function onData(e:ProgressEvent):void {
			Singleton.getInstance().dispatchEvent(new SocketEvent(SocketEvent.RECEIEVED));
		}

		private function onConnect(e:Event):void {
			trace('连接socket服务器成功！');
		}

		private function onClose(e:Event):void {
			trace('断开了和socket服务器的连接！');
		}

		private function onIOError(e:IOErrorEvent):void {
			trace('连接服务器失败，请稍候操作');
		}

		private function onSecurityError(e:SecurityErrorEvent):void {
			trace('发生沙箱安全错误！');
		}
	}
}